import React, { useState } from 'react';
import { View, Text, Modal, Pressable, StyleSheet, Alert, ActivityIndicator } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import * as DocumentPicker from 'expo-document-picker';
import { Receipt } from '../types/expense';
import { processReceiptWithOCR } from '../services/ocrService';

interface ReceiptUploaderProps {
  visible: boolean;
  onClose: () => void;
  onUpload: (receipt: Receipt) => void;
}

export default function ReceiptUploader({ visible, onClose, onUpload }: ReceiptUploaderProps) {
  const [loading, setLoading] = useState(false);

  // 从相册选择图片
  const pickImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: false,
        quality: 0.8,
      });

      if (!result.canceled && result.assets && result.assets.length > 0) {
        await processImage(result.assets[0].uri);
      }
    } catch (error) {
      Alert.alert('错误', '选择图片失败');
      console.error(error);
    }
  };

  // 拍照获取图片
  const takePhoto = async () => {
    try {
      const cameraPermission = await ImagePicker.requestCameraPermissionsAsync();
      
      if (cameraPermission.status !== 'granted') {
        Alert.alert('权限不足', '需要相机权限才能拍照');
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        allowsEditing: true,
        quality: 0.8,
      });

      if (!result.canceled && result.assets && result.assets.length > 0) {
        await processImage(result.assets[0].uri);
      }
    } catch (error) {
      Alert.alert('错误', '拍照失败');
      console.error(error);
    }
  };

  // 从文件选择PDF
  const pickDocument = async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: ['application/pdf', 'image/*'],
        copyToCacheDirectory: true,
      });

      if (result.canceled === false && result.assets && result.assets.length > 0) {
        await processImage(result.assets[0].uri);
      }
    } catch (error) {
      Alert.alert('错误', '选择文件失败');
      console.error(error);
    }
  };

  // 处理图片
  const processImage = async (uri: string) => {
    try {
      setLoading(true);
      
      // 调用OCR服务处理图片
      const receiptData = await processReceiptWithOCR(uri);
      
      // 创建发票对象
      const newReceipt: Receipt = {
        id: Date.now().toString(),
        imageUri: uri,
        uploadDate: new Date().toISOString().split('T')[0],
        ...receiptData,
      };
      
      // 提交发票数据
      onUpload(newReceipt);
      onClose();
    } catch (error) {
      Alert.alert('错误', '处理发票失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      visible={visible}
      transparent
      animationType="slide"
      onRequestClose={onClose}
    >
      <View className="flex-1 justify-end bg-black/50">
        <View className="bg-white rounded-t-3xl p-6">
          <View className="items-center mb-6">
            <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
            <Text className="text-xl font-bold">添加发票</Text>
          </View>

          {loading ? (
            <View className="items-center py-8">
              <ActivityIndicator size="large" color="#3B82F6" />
              <Text className="mt-4 text-gray-500">正在处理发票...</Text>
            </View>
          ) : (
            <View className="gap-4">
              <Pressable 
                className="flex-row items-center p-4 bg-blue-50 rounded-xl"
                onPress={pickDocument}
              >
                <View className="w-10 h-10 bg-blue-100 rounded-full items-center justify-center">
                  <Ionicons name="document-outline" size={24} color="#3B82F6" />
                </View>
                <View className="ml-3">
                  <Text className="text-lg font-semibold">从文件中选择</Text>
                  <Text className="text-gray-500">选择PDF或图片文件</Text>
                </View>
              </Pressable>

              <Pressable 
                className="flex-row items-center p-4 bg-green-50 rounded-xl"
                onPress={pickImage}
              >
                <View className="w-10 h-10 bg-green-100 rounded-full items-center justify-center">
                  <Ionicons name="images-outline" size={24} color="#10B981" />
                </View>
                <View className="ml-3">
                  <Text className="text-lg font-semibold">从相册中选择</Text>
                  <Text className="text-gray-500">从手机相册选择图片</Text>
                </View>
              </Pressable>

              <Pressable 
                className="flex-row items-center p-4 bg-purple-50 rounded-xl"
                onPress={takePhoto}
              >
                <View className="w-10 h-10 bg-purple-100 rounded-full items-center justify-center">
                  <Ionicons name="camera-outline" size={24} color="#8B5CF6" />
                </View>
                <View className="ml-3">
                  <Text className="text-lg font-semibold">拍照</Text>
                  <Text className="text-gray-500">使用相机拍摄发票照片</Text>
                </View>
              </Pressable>

              <Pressable 
                className="mt-2 py-3 items-center bg-gray-100 rounded-xl"
                onPress={onClose}
              >
                <Text className="text-gray-600 font-semibold">取消</Text>
              </Pressable>
            </View>
          )}
        </View>
      </View>
    </Modal>
  );
} 